﻿<?php
include_once(dirname(__FILE__).'/Log.class.php');
class Db{
    private static $db;
    private $rows;
    private $log;
    private $db_link;
    private $db_host;
    private $db_use;
    private $db_passwd;

    private function __construct(){
        $this->db_host = "127.0.0.1";
        $this->db_name = 'eve';
        $this->db_use = "root";
        $this->db_passwd = "7511xxw";
        $this->rows = 0;
        $this->log = Log::getInstance();
        try{
            $this->db_connect();
        }catch(Exception $e){
            $this->log->log($e->getMessage());
            die();
        }
    }
    public static function getInstance(){
        if(self::$db == null)
        {
            self::$db = new Db();
            return self::$db;
        }
        else
            return self::$db;
    }
    public function getRows(){
        return $this->rows;
    }
    private function db_connect(){
        $this->db_link = mysql_connect($this->db_host,$this->db_use,$this->db_passwd);
        if($this->db_link == FALSE)
            throw new Exception(mysql_error());
        if(mysql_select_db($this->db_name,$this->db_link)==null)
            throw new Exception(mysql_error());
    }
    public function insert($sql){
        try{
            if(mysql_query('SET NAMES utf8') == FALSE)
                throw new Exception(mysql_error());
            if(mysql_query($sql) == FALSE)
                throw new Exception(mysql_error());
        }catch(Exception $e){
            $this->log->log($e->getMessage());
            die();
        }
    }
    public function update($sql){
        try{
            if(mysql_query('SET NAMES utf8') == FALSE)
                throw new Exception(mysql_error());
            if(mysql_query($sql) == FALSE)
                throw new Exception(mysql_error());
        }catch(Exception $e){
            $this->log->log($e->getMessage());
            die();
        }
    }
    public function db_query($sql,$callback){
        try{
            if(mysql_query("SET NAMES utf8") == FALSE)
                throw new Exception(mysql_error());
            $result = mysql_query($sql);
            $this->rows = mysql_num_rows($result);
            if($result == FALSE)
                throw new Exception(mysql_error());
        }catch(Exception $e){
            $this->log->log($e->getMessage());
            die();
        }
        $query_result = array();
        while($row = mysql_fetch_object($result))
            array_push($query_result,$row);
        $return_value = $callback($query_result);
        return $return_value;
    }
}
?>